﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MultiDAQ_Analysis.Util
{
    public static class CRC32
    {
        private static readonly uint[] Table;

        static CRC32()
        {
            Table = new uint[256];

            const uint poly = 0x1CDF4421;           // 原始（标准）多项式
            uint reflectedPoly = Reflect(poly);     // 反射多项式为右低位形式

            for (uint i = 0; i < Table.Length; ++i)
            {
                uint temp = i;
                for (int j = 0; j < 8; ++j)
                    temp = (temp & 1) != 0 ? (reflectedPoly ^ (temp >> 1)) : (temp >> 1);
                Table[i] = temp;
            }
        }

        private static uint Reflect(uint value)
        {
            uint result = 0;
            for (int i = 0; i < 32; ++i)
            {
                if ((value & 1) != 0)
                    result |= (1u << (31 - i));
                value >>= 1;
            }
            return result;
        }

        public static uint Compute(byte[] data)
        {
            uint crc = 0xFFFFFFFF;
            foreach (byte b in data)
                crc = Table[(crc ^ b) & 0xFF] ^ (crc >> 8);
            return ~crc;
        }
    }
}

